import express, { Request, Response } from "express";
import DingtalkRequest from "./util/dingtalkRequest";
import { YundocApi } from "./util/yundocRequest";
const iconv = require("iconv-lite");
const app = express();
const PORT = process.env.PORT || 3000;
// 处理跨域请求
app.use((req: Request, res: Response, next: any) => {
	res.header("Access-Control-Allow-Origin", "*");
	res.header(
		"Access-Control-Allow-Headers",
		"Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild"
	);
	res.header("Access-Control-Allow-Methods", "PUT, POST, GET, DELETE, OPTIONS");
	if (req.method == "OPTIONS") {
		res.sendStatus(200);
	} else {
		next();
	}
});
// 静态资源目录
app.use(express.static("uploads"));
app.get("/", (req: Request, res: Response) => {
	res.send("Hello, World!");
});

// 钉钉组织架构数据同步
app.post("/dingtalk/syncData", (req: Request, res: Response) => {
	// 获取钉钉开放平台access_token
	let dingtalkRequest = new DingtalkRequest();
	let accessToken = dingtalkRequest.getAccessToken();
	// 查询钉钉根部门
	let rootDept: any = dingtalkRequest.get("/topapi/v2/department/get", {
		access_token: accessToken,
		id: 1,
	});
	console.log(JSON.stringify(rootDept), "rootDept");
	// 查询钉钉根部门用户列表
	let rootDeptUserListReq: any = dingtalkRequest.post(
		"topapi/user/listsimple?access_token=" + accessToken,
		{
			dept_id: rootDept.id,
			cursor: 0,
			size: 100,
		}
	);
	let rootDeptUserList = rootDeptUserListReq.result.list;
	// 查询云文档根部门
	let yundocRootDept: any;
	// 在云文档根部门下创建用户
	let request = new YundocApi();
	rootDeptUserList.foreach((user: any) => {
		let createUserBody = {
			account: user.name,
			nick_name: user.name,
			password: "123456",
			third_platform_id: "1",
			third_union_id: user.userid,
		};
		request.createUser(createUserBody);
	});
	// 递归查询钉钉子部门id
	let subDeptIdListReq: any = dingtalkRequest.post(
		"/topapi/v2/department/listsubid?access_token=" + accessToken,
		{ access_token: accessToken, dept_id: 1 }
	);
	let subDeptIdList = subDeptIdListReq.result.dept_id_list;
	if (subDeptIdList.length > 0) {
		// 遍历钉钉子部门id
		for (let i = 0; i < subDeptIdList.length; i++) {
			// 查询钉钉子部门详情和用户信息，并同步数据到云文档
			let subDept = dingtalkRequest.recursionSyncSubDeptAndUser(
				accessToken,
				subDeptIdList[i],
				yundocRootDept.id
			);
		}
	}
	res.json({
		code: 200,
		message: "同步成功",
		data: [],
	});
});

app.listen(PORT, () => {
	console.log(`Server is running on port ${PORT}`);
});
